package org.example.module.api.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.example.common.base.request.CommonRequestParam;
import org.example.common.base.response.Result;
import org.example.common.router.WarehouseFactory;
import org.example.module.api.model.outbound.CreateOutboundReqParam;
import org.example.module.api.model.outbound.CreateOutboundResParam;
import org.example.module.api.service.WarehouseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.function.Function;

@Api(tags = "统一API接口")
@Slf4j
@RestController
@RequestMapping("/api")
public class UnifiedController {

    @Autowired
    WarehouseFactory warehouseFactory;

    @ApiOperation("创建出库单")
    @PostMapping("createOutbound")
    public Result<CreateOutboundResParam> createOutbound(@RequestBody @Validated CommonRequestParam<CreateOutboundReqParam> param) {
        log.info("创建出库单: {}", param);
        return handleRequest(param, warehouseService -> warehouseService.createOutbound(param));
    }

    private  <T> T handleRequest(CommonRequestParam param, Function<WarehouseService, T> serviceAction) {
        try {
            // 仓库校验
            if (StringUtils.isEmpty(param.getCode())) {
                log.error("仓库编码为空或不存在: {}", param.getCode());
                throw new RuntimeException("仓库编码为空或不存在");
            }

            // 获取仓库服务
            WarehouseService warehouseService = warehouseFactory.getWarehouseService(param.getCode());
            if (warehouseService == null) {
                log.error("未找到指定的仓库服务: {}", param.getCode());
                throw new RuntimeException("未找到指定的仓库服务");
            }

            // 执行具体操作
            T t = serviceAction.apply(warehouseService);
            return t;
        } catch (Exception e) {
            log.error("请求出错啦", e);
            throw new RuntimeException("执行出错啦");
        } finally {
//            try {
//                // 清除threadLocal中的数据，防止OOM
//                BaseWarehouseLogUtil.remove();
//            } catch (Exception e) {
//                log.error("清除本地线程变量出错", e);
//            }
        }
    }
}
